# -*- coding: utf-8 -*-

"""
主窗口界面
"""

from PyQt5.QtWidgets import (QMainWindow, QWidget, QVBoxLayout, QHBoxLayout,
                             QPushButton, QLabel, QStackedWidget, QMenuBar,
                             QAction, QStatusBar, QFileDialog, QMessageBox,
                             QSystemTrayIcon, QStyle, qApp, QMenu, QStyleFactory,
                             QDialog, QVBoxLayout, QRadioButton, QDialogButtonBox,
                             QApplication)
from PyQt5.QtCore import Qt, QSize, QPropertyAnimation, QEasingCurve, QSettings, QStandardPaths
from PyQt5.QtGui import QIcon, QPixmap, QKeySequence, QDragEnterEvent, QDropEvent
import os

# 添加缺失的导入
from src.ai.emotion_engine import EmotionEngine
from src.gui.settings_dialog import SettingsDialog
from src.gui.game_widget import GameWidget
from PyQt5.QtWidgets import QShortcut

# 添加PuzzleSourceManager导入（将在后面实现）
from src.data.puzzle_source_manager import PuzzleSourceManager


class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        # 读取版本号
        self.version = self.get_version()
        self.setWindowTitle(f"心灵拼图 - Soul Jigsaw v{self.version}")
        self.setGeometry(100, 100, 1000, 700)
        
        # 设置接受拖放
        self.setAcceptDrops(True)
        
        # 初始化系统托盘
        self.setup_system_tray()
        
        # 设置应用程序样式以适配GNOME/KDE主题
        self.setup_theme_adaptation()
        
        # 初始化情感引擎
        self.emotion_engine = EmotionEngine()
        # 连接焦虑检测信号到场景切换槽
        
        # 创建中心部件
        self.central_widget = QWidget()
        self.setCentralWidget(self.central_widget)
        
        # 创建布局
        self.main_layout = QVBoxLayout(self.central_widget)
        
        # 创建菜单栏
        self.create_menu_bar()
        
        # 创建工具栏
        self.create_toolbar()
        
        # 创建状态栏
        self.status_bar = QStatusBar()
        self.setStatusBar(self.status_bar)
        self.status_bar.showMessage("欢迎来到心灵拼图游戏！")
        
        # 创建主界面
        self.create_main_interface()
        
        # 注册全局快捷键
        self.setup_global_shortcuts()
        
        # 启动摄像头情感检测
        self.emotion_engine.start_camera_capture()

    def setup_theme_adaptation(self):
        """设置主题自适应"""
        # 检测桌面环境
        desktop = os.environ.get('XDG_CURRENT_DESKTOP', '').lower()
        
        if 'gnome' in desktop:
            # GNOME主题适配
            self.setStyleSheet("""
                QMainWindow {
                    background-color: @theme_bg_color;
                    color: @theme_fg_color;
                }
            """)
        elif 'kde' in desktop:
            # KDE主题适配
            self.setStyleSheet("""
                QMainWindow {
                    background-color: palette(window);
                    color: palette(windowText);
                }
            """)
        
        # 使用系统默认样式
        qApp.setStyle(QStyleFactory.create("Fusion"))

    def setup_system_tray(self):
        """设置系统托盘图标"""
        if QSystemTrayIcon.isSystemTrayAvailable():
            self.tray_icon = QSystemTrayIcon(self)
            # 使用应用图标作为托盘图标
            self.tray_icon.setIcon(self.style().standardIcon(QStyle.SP_ComputerIcon))
            
            # 创建托盘菜单
            tray_menu = QMenu()
            restore_action = QAction("恢复", self)
            restore_action.triggered.connect(self.showNormal)
            quit_action = QAction("退出", self)
            quit_action.triggered.connect(self.quit_application)
            
            tray_menu.addAction(restore_action)
            tray_menu.addAction(quit_action)
            
            self.tray_icon.setContextMenu(tray_menu)
            self.tray_icon.show()
            
            # 连接托盘图标激活信号
            self.tray_icon.activated.connect(self.on_tray_icon_activated)
        else:
            self.tray_icon = None

    def on_tray_icon_activated(self, reason):
        """托盘图标激活事件处理"""
        if reason == QSystemTrayIcon.Trigger:
            # 点击托盘图标时切换窗口显示状态
            if self.isHidden() or self.isMinimized():
                self.showNormal()
                self.activateWindow()
            else:
                self.hide()

    def setup_global_shortcuts(self):
        """设置全局快捷键"""
        # 创建全局快捷键 (Ctrl+Alt+P)
        self.shortcut = QShortcut(QKeySequence("Ctrl+Alt+P"), self)
        self.shortcut.activated.connect(self.toggle_visibility)
        
    def toggle_visibility(self):
        """切换窗口可见性"""
        if self.isHidden() or self.isMinimized():
            self.showNormal()
            self.activateWindow()
        else:
            self.hide()

    def create_menu_bar(self):
        """创建菜单栏"""
        menu_bar = self.menuBar()
        
        # 文件菜单
        file_menu = menu_bar.addMenu("文件")
        
        new_game_action = QAction("新游戏", self)
        new_game_action.setShortcut("Ctrl+N")
        new_game_action.triggered.connect(self.new_game)
        file_menu.addAction(new_game_action)
        
        open_image_action = QAction("打开图片", self)
        open_image_action.setShortcut("Ctrl+O")
        open_image_action.triggered.connect(self.open_image)
        file_menu.addAction(open_image_action)
        
        # 添加从其他目录选择图片的选项
        open_from_directory_action = QAction("从目录选择图片", self)
        open_from_directory_action.triggered.connect(self.open_images_from_directory)
        file_menu.addAction(open_from_directory_action)
        
        # 添加截图功能
        screenshot_action = QAction("屏幕截图", self)
        screenshot_action.setShortcut("Ctrl+Shift+S")
        screenshot_action.triggered.connect(self.take_screenshot)
        file_menu.addAction(screenshot_action)
        
        file_menu.addSeparator()
        
        exit_action = QAction("退出", self)
        exit_action.setShortcut("Ctrl+Q")
        exit_action.triggered.connect(self.quit_application)
        file_menu.addAction(exit_action)
        
        # 游戏菜单
        game_menu = menu_bar.addMenu("游戏")
        
        settings_action = QAction("设置", self)
        settings_action.triggered.connect(self.show_settings)
        game_menu.addAction(settings_action)
        
        # 帮助菜单
        help_menu = menu_bar.addMenu("帮助")
        
        about_action = QAction("关于", self)
        about_action.triggered.connect(self.show_about)
        help_menu.addAction(about_action)
        
    def create_toolbar(self):
        """创建工具栏"""
        toolbar = self.addToolBar("工具栏")
        toolbar.setMovable(False)
        
        # 新游戏按钮
        new_game_btn = QPushButton("新游戏")
        new_game_btn.clicked.connect(self.new_game)
        toolbar.addWidget(new_game_btn)
        
        # 设置按钮
        settings_btn = QPushButton("设置")
        settings_btn.clicked.connect(self.show_settings)
        toolbar.addWidget(settings_btn)
        
    def create_main_interface(self):
        """创建主界面"""
        # 标题
        title_label = QLabel("心灵拼图")
        title_label.setAlignment(Qt.AlignCenter)
        title_label.setStyleSheet("font-size: 24px; font-weight: bold; margin: 20px;")
        self.main_layout.addWidget(title_label)
        
        # 按钮布局
        button_layout = QHBoxLayout()
        button_layout.addStretch()
        
        # 开始游戏按钮
        start_btn = QPushButton("开始游戏")
        start_btn.setFixedSize(150, 50)
        start_btn.clicked.connect(self.start_game)
        button_layout.addWidget(start_btn)
        
        # 设置按钮
        settings_btn = QPushButton("游戏设置")
        settings_btn.setFixedSize(150, 50)
        settings_btn.clicked.connect(self.show_settings)
        button_layout.addWidget(settings_btn)
        
        button_layout.addStretch()
        self.main_layout.addLayout(button_layout)
        
        # 说明文字
        info_label = QLabel("通过完成拼图来探索您的内心世界\n\n"
                           "支持拖放图片文件到此窗口直接开始游戏\n"
                           "按Ctrl+V可粘贴剪贴板中的图片\n"
                           "按Ctrl+Shift+S可进行屏幕截图")
        info_label.setAlignment(Qt.AlignCenter)
        info_label.setStyleSheet("font-size: 14px; color: gray; margin: 20px;")
        self.main_layout.addWidget(info_label)
        
    def start_game(self):
        """开始游戏"""
        # 尝试从配置的目录中获取随机图片
        from src.game_logic import GameLogic
        game_logic = GameLogic()
        image_path = None
        
        # 检查是否设置了图片目录
        image_dir = game_logic.config.get("images.puzzle_image_directory", "")
        if image_dir and os.path.exists(image_dir):
            image_path = game_logic._get_random_image_from_directory(image_dir)
            
        # 获取设置的网格大小
        grid_size = game_logic.config.get("game.default_puzzle_size", 3)
        self.game_widget = GameWidget(image_path, grid_size=grid_size)
        # 添加信号连接
        self.game_widget.game_completed.connect(self.on_game_completed)
        self.game_widget.back_to_main.connect(self.on_back_to_main)
        self.setCentralWidget(self.game_widget)
        
    def on_game_completed(self):
        """游戏完成处理"""
        from PyQt5.QtWidgets import QMessageBox
        QMessageBox.information(self, "恭喜", "拼图完成！")
        
    def on_back_to_main(self):
        """返回主菜单处理"""
        self.create_main_interface()
        self.setCentralWidget(self.central_widget)
        
    def new_game(self):
        """新游戏"""
        reply = QMessageBox.question(self, "确认", "确定要开始新游戏吗？当前进度将丢失。",
                                   QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
        if reply == QMessageBox.Yes:
            self.start_game()
            
    def open_image(self):
        """打开图片"""
        file_path, _ = QFileDialog.getOpenFileName(
            self, "选择图片", "", 
            "图片文件 (*.png *.jpg *.jpeg *.bmp *.gif)")
        if file_path:
            # 启动游戏并加载选定的图片
            from src.game_logic import GameLogic
            game_logic = GameLogic()
            grid_size = game_logic.config.get("game.default_puzzle_size", 3)
            self.game_widget = GameWidget(file_path, grid_size=grid_size)
            self.setCentralWidget(self.game_widget)
            
    def open_images_from_directory(self):
        """从目录选择图片"""
        directory = QFileDialog.getExistingDirectory(self, "选择图片目录")
        if directory:
            # 保存目录设置
            from src.game_logic import GameLogic
            game_logic = GameLogic()
            game_logic.update_image_directory_setting(directory)
            
            # 从目录中随机选择一张图片开始游戏
            image_path = game_logic._get_random_image_from_directory(directory)
            if image_path:
                grid_size = game_logic.config.get("game.default_puzzle_size", 3)
                self.game_widget = GameWidget(image_path, grid_size=grid_size)
                self.setCentralWidget(self.game_widget)
            else:
                QMessageBox.warning(self, "警告", "目录中没有找到有效的图片文件")
            
    def take_screenshot(self):
        """屏幕截图"""
        # 隐藏主窗口
        self.hide()
        
        # 等待窗口隐藏
        QApplication.processEvents()
        
        # 截图整个屏幕
        screen = QApplication.primaryScreen()
        if screen:
            screenshot = screen.grabWindow(0)
            # 显示主窗口
            self.show()
            
            # 保存截图到临时文件
            temp_path = os.path.join(QStandardPaths.writableLocation(QStandardPaths.TempLocation), "screenshot.png")
            screenshot.save(temp_path)
            
            # 使用截图开始游戏
            from src.game_logic import GameLogic
            game_logic = GameLogic()
            grid_size = game_logic.config.get("game.default_puzzle_size", 3)
            self.game_widget = GameWidget(temp_path, grid_size=grid_size)
            self.setCentralWidget(self.game_widget)
        else:
            self.show()
            QMessageBox.warning(self, "错误", "无法获取屏幕截图")
            
    def show_settings(self):
        """显示设置对话框"""
        settings_dialog = SettingsDialog(self)
        
        # 读取当前设置
        settings = QSettings("SoulJigsaw", "Settings")
        close_behavior = settings.value("close_behavior", "")
        
        # 根据当前设置初始化单选按钮
        if close_behavior == "minimize":
            settings_dialog.set_close_behavior("minimize")
        elif close_behavior == "close":
            settings_dialog.set_close_behavior("close")
        
        if settings_dialog.exec_() == QDialog.Accepted:
            # 保存关闭行为设置
            close_behavior = settings_dialog.get_close_behavior()
            if close_behavior:
                settings.setValue("close_behavior", close_behavior)
        
    def show_about(self):
        """显示关于对话框"""
        version = self.get_version()
        QMessageBox.about(self, "关于心灵拼图",
                         f"心灵拼图 v{version}\n\n"
                         "一个AI驱动的拼图游戏，帮助您探索内心世界。\n\n"
                         "© 2023 心灵拼图开发团队")
                         
    def quit_application(self):
        """退出应用程序"""
        # 停止摄像头捕获
        self.emotion_engine.stop_camera_capture()
        qApp.quit()
        
    def closeEvent(self, event):
        """窗口关闭事件，处理系统托盘最小化"""
        # 读取设置
        settings = QSettings("SoulJigsaw", "Settings")
        close_behavior = settings.value("close_behavior", "")
        
        # 如果已经设置了关闭行为，则直接应用
        if close_behavior == "close":
            self.emotion_engine.stop_camera_capture()
            event.accept()
            return
        elif close_behavior == "minimize":
            if self.tray_icon and self.tray_icon.isVisible():
                # 最小化到系统托盘而不是退出
                self.hide()
                self.tray_icon.showMessage(
                    "心灵拼图",
                    "程序已在系统托盘中运行",
                    QSystemTrayIcon.Information,
                    2000
                )
                event.ignore()
                return
        
        # 如果没有设置或设置无效，显示选择对话框
        dialog = CloseOptionDialog(self)
        result = dialog.exec_()
        
        if result == QDialog.Accepted:
            # 用户选择直接关闭
            # 保存用户的选择
            if dialog.close_radio.isChecked():
                settings.setValue("close_behavior", "close")
            elif dialog.minimize_radio.isChecked():
                settings.setValue("close_behavior", "minimize")
                
            self.emotion_engine.stop_camera_capture()
            event.accept()
        else:
            # 用户选择最小化到托盘
            # 保存用户的选择
            if dialog.close_radio.isChecked():
                settings.setValue("close_behavior", "close")
            elif dialog.minimize_radio.isChecked():
                settings.setValue("close_behavior", "minimize")
                
            if self.tray_icon and self.tray_icon.isVisible():
                # 最小化到系统托盘而不是退出
                self.hide()
                self.tray_icon.showMessage(
                    "心灵拼图",
                    "程序已在系统托盘中运行",
                    QSystemTrayIcon.Information,
                    2000
                )
                event.ignore()
            else:
                # 如果没有托盘图标，则直接关闭
                self.emotion_engine.stop_camera_capture()
                event.accept()
                
    def dragEnterEvent(self, event: QDragEnterEvent):
        """拖拽进入事件"""
        if event.mimeData().hasUrls():
            # 检查是否是图片文件
            urls = event.mimeData().urls()
            for url in urls:
                if url.isLocalFile():
                    file_path = url.toLocalFile()
                    if file_path.lower().endswith(('.png', '.jpg', '.jpeg', '.bmp', '.gif')):
                        event.acceptProposedAction()
                        return
        event.ignore()
        
    def dropEvent(self, event: QDropEvent):
        """拖拽放下事件"""
        if event.mimeData().hasUrls():
            urls = event.mimeData().urls()
            for url in urls:
                if url.isLocalFile():
                    file_path = url.toLocalFile()
                    if file_path.lower().endswith(('.png', '.jpg', '.jpeg', '.bmp', '.gif')):
                        # 处理拖放的图片文件
                        from src.game_logic import GameLogic
                        game_logic = GameLogic()
                        grid_size = game_logic.config.get("game.default_puzzle_size", 3)
                        self.game_widget = GameWidget(file_path, grid_size=grid_size)
                        self.setCentralWidget(self.game_widget)
                        return
        event.ignore()
        
    def keyPressEvent(self, event):
        """按键事件处理"""
        # 处理Ctrl+V粘贴图片
        if event.modifiers() == Qt.ControlModifier and event.key() == Qt.Key_V:
            clipboard = QApplication.clipboard()
            if clipboard.mimeData().hasImage():
                # 从剪贴板获取图片
                image = clipboard.image()
                if not image.isNull():
                    # 保存到临时文件
                    temp_path = os.path.join(QStandardPaths.writableLocation(QStandardPaths.TempLocation), "clipboard_image.png")
                    image.save(temp_path)
                    from src.game_logic import GameLogic
                    game_logic = GameLogic()
                    grid_size = game_logic.config.get("game.default_puzzle_size", 3)
                    self.game_widget = GameWidget(temp_path, grid_size=grid_size)
                    self.setCentralWidget(self.game_widget)
                    return
        super().keyPressEvent(event)

    def get_version(self):
        """获取应用版本号"""
        version_file = "VERSION"
        try:
            with open(version_file, 'r') as f:
                return f.read().strip()
        except FileNotFoundError:
            return "1.0.0"  # 默认版本号


class CloseOptionDialog(QDialog):
    """关闭选项对话框"""
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setWindowTitle("关闭确认")
        self.setFixedSize(300, 150)
        
        layout = QVBoxLayout(self)
        
        label = QLabel("您希望如何关闭应用程序？")
        label.setAlignment(Qt.AlignCenter)
        layout.addWidget(label)
        
        # 选项按钮
        self.minimize_radio = QRadioButton("最小化到系统托盘")
        self.close_radio = QRadioButton("直接关闭应用程序")
        
        # 默认选择最小化到托盘
        self.minimize_radio.setChecked(True)
        
        layout.addWidget(self.minimize_radio)
        layout.addWidget(self.close_radio)
        
        # 按钮框
        button_box = QDialogButtonBox(
            QDialogButtonBox.Ok | QDialogButtonBox.Cancel
        )
        button_box.accepted.connect(self.accept)
        button_box.rejected.connect(self.reject)
        layout.addWidget(button_box)
        
    def accept(self):
        """确认选择"""
        if self.close_radio.isChecked():
            super().accept()
        else:
            super().reject()